package jmu.rzk.shippingmanagementsystem.service.impl;

import jmu.rzk.shippingmanagementsystem.dao.UserRepository;
import jmu.rzk.shippingmanagementsystem.entity.User;
import jmu.rzk.shippingmanagementsystem.exception.BusinessException;
import jmu.rzk.shippingmanagementsystem.service.UserService;
import jmu.rzk.shippingmanagementsystem.vo.request.LoginRequest;
import jmu.rzk.shippingmanagementsystem.vo.request.RegisterRequest;
import jmu.rzk.shippingmanagementsystem.vo.response.UserResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    @Transactional
    public UserResponse register(RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new BusinessException("用户名已存在");
        }
        
        // 创建用户实体
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(registerRequest.getPassword()); // 实际应用中应对密码进行加密
        user.setName(registerRequest.getName());
        user.setPhone(registerRequest.getPhone());
        user.setEmail(registerRequest.getEmail());
        user.setStatus(1); // 默认启用
        
        // 保存用户
        userRepository.save(user);
        
        // 返回用户响应
        return UserResponse.fromEntity(user);
    }
    
    @Override
    public UserResponse login(LoginRequest loginRequest) {
        // 根据用户名查询用户
        Optional<User> userOptional = userRepository.findByUsernameAndStatus(loginRequest.getUsername(), 1);
        
        // 检查用户是否存在
        if (userOptional.isEmpty()) {
            throw new BusinessException("用户不存在或已被禁用");
        }
        
        User user = userOptional.get();
        
        // 检查密码是否正确（实际应用中应对密码进行加密比对）
        if (!user.getPassword().equals(loginRequest.getPassword())) {
            throw new BusinessException("密码错误");
        }
        
        // 返回用户响应
        return UserResponse.fromEntity(user);
    }
    
    @Override
    public UserResponse getUserById(Long id) {
        Optional<User> userOptional = userRepository.findById(id);
        
        if (userOptional.isEmpty()) {
            throw new BusinessException("用户不存在");
        }
        
        return UserResponse.fromEntity(userOptional.get());
    }
    
    @Override
    @Transactional
    public UserResponse updateUser(Long id, User userUpdate) {
        Optional<User> userOptional = userRepository.findById(id);
        
        if (userOptional.isEmpty()) {
            throw new BusinessException("用户不存在");
        }
        
        User user = userOptional.get();
        
        // 只更新非空字段
        if (userUpdate.getName() != null) {
            user.setName(userUpdate.getName());
        }
        if (userUpdate.getPhone() != null) {
            user.setPhone(userUpdate.getPhone());
        }
        if (userUpdate.getEmail() != null) {
            user.setEmail(userUpdate.getEmail());
        }
        if (userUpdate.getStatus() != null) {
            user.setStatus(userUpdate.getStatus());
        }
        
        user.setUpdateTime(LocalDateTime.now());
        
        userRepository.save(user);
        
        return UserResponse.fromEntity(user);
    }
    
    @Override
    @Transactional
    public void deleteUser(Long id) {
        if (!userRepository.existsById(id)) {
            throw new BusinessException("用户不存在");
        }
        
        userRepository.deleteById(id);
    }
    
    @Override
    public List<UserResponse> getAllUsers() {
        List<User> users = userRepository.findAll();
        
        return users.stream()
                .map(UserResponse::fromEntity)
                .collect(Collectors.toList());
    }
} 